package us.sunrisemorning.bilibili_live_chat;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import us.sunrisemorning.bilibili_live_chat.ws.BiliBiliWebSocketClient;

import java.util.HashMap;
import java.util.Map;

public class BiliBiliLiveChatClient {
    private int roomId;
    private BiliBiliLiveChatMessageHandler messageHandler;

    public BiliBiliLiveChatClient(int roomId, BiliBiliLiveChatMessageHandler messageHandler) {
        this.roomId = roomId;
        this.messageHandler = messageHandler;
    }

    public void connect() {
        Map<String, Object> params = MapUtil.builder(new HashMap<String, Object>())
                .put("id", roomId)
                .put("type", 0)
                .build();
        String responseText = HttpUtil.get(Constants.API_GETDANMUINFO_URL, params);
        JSONObject danmuInfo = JSONUtil.parseObj(responseText);

        String token = danmuInfo.getJSONObject("data").getStr("token");

        JSONObject serverInfo = danmuInfo.getJSONObject("data").getJSONArray("host_list").getJSONObject(0);

        String serverUrl = "ws://" + serverInfo.getStr("host") + ":" + serverInfo.getStr("ws_port") + "/sub";

        BiliBiliWebSocketClient client = new BiliBiliWebSocketClient(serverUrl, roomId, token, messageHandler);
        client.connect();
    }
}